﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.DirectoryServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Microsoft.AnalysisServices.AdomdClient;
using Microsoft.SharePoint.Utilities;

namespace KoPages.CONTROLTEMPLATES.userControls
{

    public partial class BI_CashAtYear : UserControl
    {

        #region Members
        #endregion

        #region App Settings
        static public string GetAppSetting(String mName)
        {
            String vStr = null;

            string strPath =
@"C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config";
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(strPath);
            XmlNode node = xmlDoc.SelectSingleNode(@"/configuration/appSettings");
            foreach (XmlNode keynode in node.ChildNodes)
            {
                string keyStr = keynode.Attributes["key"].Value;
                if (keyStr == mName)
                {
                    vStr = keynode.Attributes["value"].Value;
                    break;
                }
            }

            if (String.IsNullOrEmpty(vStr))
                vStr = "";
            return vStr;
        }
        #endregion App Settings

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Microsoft.SharePoint.SPContext.Current == null
                || Microsoft.SharePoint.SPContext.Current.Web == null
                || Microsoft.SharePoint.SPContext.Current.Web.CurrentUser == null)
            {
                return;
            }

            //bool IsUID_Exist = false;
            //KoAD ad = new KoAD();
            //string CurUID = Microsoft.SharePoint.SPContext.Current.Web.CurrentUser.LoginName;
            //string[] stringSeparators = new string[] { @"\" };
            //string[] strTmp = CurUID.Split(stringSeparators, StringSplitOptions.None);
            //CurUID = strTmp[1];
            //ad.IsExistUserInGroup(ref IsUID_Exist, CurUID, "acs_app20_olap");

            //if (IsUID_Exist == false && CurUID != @"morozovsa")
            //    return;

            string connStr = GetAppSetting(@"BIConnect");
            DateTime dt = DateTime.Now;
            int Year = dt.Year;
            int Month = dt.Month;
            DataTable tbl = null;
            Exception err = new BI_SQL_CashAtYear().Get(ref tbl, Year, Month);
            StringBuilder sb = new StringBuilder();
            if (err == null)
            {
                err = new BI_SQL_CashAtYear().MakeHTML_001(ref sb, ref tbl);
                if (err == null)
                    oBody.Text = sb.ToString();
                else
                {
                    sb.Append(@"<p>Ошибка : " + err.Message + @"</p>");
                    oBody.Text = sb.ToString();
                }
            }
            else
            {
                sb.Append(@"<p>Ошибка : " + err.Message + @"</p>");
                oBody.Text = sb.ToString();
            }

        }

    }

    public class BI_SQL_CashAtYear
    {

        #region Common

        public static string MakeDT_Y_M(int Year, int Month)
        {
            return string.Format("{0:0000}{1:00}", Year, Month);
        }

        public string EncodeValue(Decimal val)
        {
            string ret = "";
            string str = val.ToString("C");
            if (str.Length > 5)
                ret = str.Substring(0, str.Length - 5);
            return ret;
        }

        public Exception GetErrList(ref byte[] parData, ref List<string> parErrList)
        {
            Exception ret = null;
            try
            {
                StringBuilder sb = new StringBuilder();
                foreach (byte bt in parData)
                    sb.Append((char)bt);
                string str = sb.ToString();
                XDocument xErrors = XDocument.Parse(str);
                var query = from g in xErrors.Descendants("Errors")
                            select new
                            {
                                errName = (string)g.Element("Err")
                            };
                foreach (var node in query)
                {
                    if (node.errName == null)
                    {
                        // Errors not found
                    }
                    else
                    {
                        parErrList.Add(node.errName);
                    }
                }
            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, err);
            }
            return ret;
        }

        #endregion

        public Exception Get(ref DataTable tbl, int parYear, int parMonth)
        {
            Exception ret = null;
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.Headers["Cache-Control"] = "no-cache";
                wc.UseDefaultCredentials = false;
                wc.Credentials = new System.Net.NetworkCredential("anonymous", "janeDoe@contoso.com");
                wc.UseDefaultCredentials = false;
                byte[] data = wc.DownloadData(
@"http://sp.korablik.local:88/ws/BI/CashAtYear.aspx?guid=" + new Guid().ToString());
                if (tbl == null)
                    tbl = new DataTable("tbl");
                if (data.Length > 0)
                {
                    using (System.IO.MemoryStream xmlStream = new System.IO.MemoryStream())
                    {
                        xmlStream.Write(data, 0, data.Length);
                        xmlStream.Position = 0;
                        tbl.ReadXml(xmlStream);
                        xmlStream.Position = 0;

                        List<string> errList = new List<string>();
                        GetErrList(ref data, ref errList);
                        if (errList.Count > 0)
                            throw new Exception(errList[0]);
                    }
                }
                else
                    throw new Exception(@"Web Service http://sp.korablik.local:88 не вернул данных");
            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, err);
            }
            return ret;
        }

        public Exception MakeHTML_001(ref StringBuilder sb, ref DataTable tbl)
        {

            #region Init

            Exception ret = null;
            DateTime dtNow = DateTime.Now;
            string dtStr = dtNow.Month.ToString() + @" / " + dtNow.Year.ToString();

            string clr = "#FFFFCC", clr1 = "#FFFFCC", clr2 = "#FFFFFF";

            #endregion

            sb.Append("Динамика ; Сегодня : " + dtStr + @" .<br />" +
@"<TABLE width='600' style='BORDER-COLLAPSE: collapse;background-color: #FFFFFF; color: #FFFFFF; font-weight: bold;'
id=ctl00_GridView1 border=1 rules=all cellSpacing=0><TBODY>");

            sb.Append(
@"<TR style='background-color: #808080' >
<TH scope=col>&nbsp;&nbsp;Месяц</TH>");

            int col_start = 1;
            if (tbl.Columns.Count > 4)
                col_start = tbl.Columns.Count - 3;

            for (int i = col_start; i < tbl.Columns.Count; i++)
                sb.Append(@"<TH scope=col>&nbsp;" + tbl.Columns[i].Caption + @"</TH>");

            int cnt = 0;
            string r_bottom = "";
            foreach (DataRow r in tbl.Rows)
            {
                cnt++;

                string name = "";
                if (r["Month"] != null)
                    name = r["Month"].ToString();
                Decimal value = 0;
                string str = "";

                if (cnt % 2 == 0) clr = clr1;
                else clr = clr2;
                if (name == "Все") clr = "#AAAAAA";

                str +=
@"<TR style='background-color: " + clr + @"; font-size: small; font-weight: bold; color: #003366;'>";

                str += @"<TD align='left'>" + name + @"&nbsp;&nbsp;</TD>";

                for (int i = col_start; i < tbl.Columns.Count; i++)
                {
                    if (r[i] != null && r[i] != DBNull.Value)
                        value = Convert.ToDecimal(r[i]);
                    else
                        value = 0;

                    str +=
@"<TD align='right'>" + SPEncode.HtmlEncode(EncodeValue(value)) + @"&nbsp;&nbsp;</TD>";

                }

                str += @"</TR>";

                if (cnt == 1)
                    r_bottom = str;
                else
                    sb.Append(str);
                
            }

            sb.Append(r_bottom);
            sb.Append(@"</TBODY></TABLE>");

            return ret;
        }

    }

}
